package com.ihrm.system.service;

import com.ihrm.common.service.BaseService;
import com.ihrm.common.util.IdWorker;
import com.ihrm.common.util.PermissionConstants;
import com.ihrm.domain.system.Permission;
import com.ihrm.domain.system.Role;
import com.ihrm.system.dao.PermissionDao;
import com.ihrm.system.dao.RoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RoleService extends BaseService{
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 1,保存部门
     */
    public void add(Role role){
        String id = idWorker.nextId()+"";
        role.setId(id);
        roleDao.save(role);
    }

    /**
     * 2，更新部门
     */
    public void update(Role role){
        Role target = roleDao.findById(role.getId()).get();
        //设置部门属性
        target.setDescription(role.getDescription());
        target.setName(role.getName());
        //更新部门
        roleDao.save(target);
    }

    /**
     * 3，根据id查询部门
     */
    public Role findById(String id){
        return roleDao.findById(id).get();
    }

    public List<Role> findAll(String companyId){

        return roleDao.findAll(getSpec(companyId));
    }

    public Page<Role> findByPage(String companyId,int page,int size){
        return roleDao.findAll(getSpec(companyId),PageRequest.of(page-1,size));
    }

    /**
     * 5，根据id删除部门
     */
    public void deleteById(String id){
        roleDao.deleteById(id);
    }

    public void assignPerm(String roleId, List<String> permIds) {
        Role role = roleDao.findById(roleId).get();
        Set<Permission> set = new HashSet<>();
        for (String permId : permIds) {
            Permission permission = permissionDao.findById(permId).get();
            List<Permission> apiList = permissionDao.findByTypeAndPid(PermissionConstants.PY_API, permission.getId());
            set.addAll(apiList);
            set.add(permission);
        }
        role.setPermissions(set);
        roleDao.save(role);
    }
}
